package com.xin.springcloudconsumer.controller;


import com.xin.springcloudconsumer.config.ProjectUrlConfig;
import com.xin.springcloudconsumer.utils.KeyUtil;
import com.xin.springcloudconsumer.utils.UploadUtils;
import com.xin.springcloudconsumer.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zz on 2017/8/11.
 */
@RestController
@Slf4j
public class UploadController {

    public static final String ROOT = "upload-dir";  //文件夹名
    private final ResourceLoader resourceLoader;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @Autowired
    public UploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }




    //显示图片的方法关键 匹配路径像 localhost:8080/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png
    @RequestMapping("/{filename:.+}")
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {

            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(projectUrlConfig.getPhotodir(), filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /*第一种上传方法,在项目根目录,但是打包成jar包运行则失败*/
    @RequestMapping("/upload")
    public ResultVO<List<String>> handleFileUpload(@RequestParam("file") MultipartFile file,
                                                   RedirectAttributes redirectAttributes, HttpServletRequest request) {

        String orgname=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName= KeyUtil.genUniqueKey()+orgname;
        if (!file.isEmpty()) {
            try {
                Files.copy(file.getInputStream(), Paths.get(projectUrlConfig.getPhotodir(), fileName));
                redirectAttributes.addFlashAttribute("message",
                        "You successfully uploaded " + fileName + "!");
            } catch (IOException|RuntimeException e) {
                redirectAttributes.addFlashAttribute("message", "Failued to upload " + fileName+ " => " + e.getMessage());
                log.info("【上传图片失败】");
                e.printStackTrace();
            }
        } else {
            redirectAttributes.addFlashAttribute("message", "Failed to upload " + fileName + " because it was empty");
        }
            ResultVO resultVO=new ResultVO();
            resultVO.setCode(0);
            List<String> list=new ArrayList<>();
            list.add(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"+fileName);
            resultVO.setData(list);
//            return "\"{errno:0,data:['"+request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/myboke/"+file.getOriginalFilename()+"'] }\"";
        return  resultVO;
}

    /**
     * 第二种上传方法,直接上传到磁盘中(使用中)
     * @param files
     * @return
     */
    @RequestMapping(value="/multipleSave", method= RequestMethod.POST )
    @ResponseBody
    public ResultVO<String> multipleSave(@RequestParam("file") MultipartFile files,
                                               HttpServletRequest request){
//        String fileName = null;
//        String msg = "";
        ResultVO<String> resultVO = UploadUtils.upload(files, request,projectUrlConfig.getPhotodir());
        return resultVO;
    }

}

